package cn.kbyue.demo.gatewaydemo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author XL
 * @version 0.1
 * @date 2022/6/11 0:02
 */
@Configuration
public class SSLConfig {

    @Value("${server.port}")
    private int serverPort;

    @PostConstruct
    public void startRedirectServer() {
        NettyReactiveWebServerFactory httpNettyReactiveWebServerFactory = new NettyReactiveWebServerFactory();
        httpNettyReactiveWebServerFactory.getWebServer((request, response) -> {
            URI uri = request.getURI();
            URI httpsUri;
            try {
                httpsUri = new URI("https", uri.getUserInfo(), uri.getHost(), serverPort, uri.getPath(), uri.getQuery(), uri.getFragment());
            } catch (URISyntaxException e) {
                return Mono.error(e);
            }
            response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
            response.getHeaders().setLocation(httpsUri);
            return response.setComplete();
        }).start();
    }

    // 以下配置方式不支持 websocket
    // @Bean
    // public TomcatServletWebServerFactory serverFactory() {
    //     TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
    //         @Override
    //         protected void postProcessContext(Context context) {
    //             SecurityConstraint constraint = new SecurityConstraint();
    //             constraint.setUserConstraint("CONFIDENTIAL");
    //             SecurityCollection collection = new SecurityCollection();
    //             collection.addPattern("/*");
    //             constraint.addCollection(collection);
    //             context.addConstraint(constraint);
    //         }
    //     };
    //     tomcat.addAdditionalTomcatConnectors(httpConnector());
    //     return tomcat;
    // }
    //
    // @Bean
    // public Connector httpConnector() {
    //     Connector connector = new Connector();
    //     connector.setScheme("http");
    //     connector.setPort(10082);
    //     connector.setSecure(false);
    //     connector.setRedirectPort(443);
    //     return connector;
    // }
}
